#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_STUDENTS 100
#define CLEAN_INPUT() while (getchar() != '\n')
typedef struct {
    char id[20];
    char name[50];
    char academy[50];
    char className[20];
    char gender[10];
    int age;
    char idNumber[20];
} Student;
Student students[MAX_STUDENTS];
int studentCount = 0;
// 跨平台清屏
void clearScreen() {
    system("clear"); // Windows系统可改为 system("cls");
}
// 安全等待按键
void waitKey() {
    printf("按回车键继续...");
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}
// 从文件加载数据（修改后）
void loadFromFile() {
    FILE *file = fopen("student.txt", "r");
    if (file == NULL) {
        printf("无法打开文件\n");
        return;
    }

    studentCount = 0; // 重置计数器
    
    while (studentCount < MAX_STUDENTS && 
           fscanf(file, "%19[^,],%49[^,],%49[^,],%19[^,],%9[^,],%d,%19s",
                  students[studentCount].id,
                  students[studentCount].name,
                  students[studentCount].academy,
                  students[studentCount].className,
                  students[studentCount].gender,
                  &students[studentCount].age,
                  students[studentCount].idNumber) == 7) {
        studentCount++;
    }

    fclose(file);
}
// 保存数据到文件（修改后）
void saveToFile() {
    FILE *file = fopen("student.txt", "w");
    if (!file) {
        perror("保存失败"); // 会打印具体错误原因
        return;
    }

    for (int i = 0; i < studentCount; i++) {
        fprintf(file, "%s,%s,%s,%s,%s,%d,%s\n",
                students[i].id,
                students[i].name,
                students[i].academy,
                students[i].className,
                students[i].gender,
                students[i].age,
                students[i].idNumber);
    }

    fclose(file);
    printf("成功保存 %d 条记录到 student.txt\n", studentCount);
}

// 添加学生
void addStudent() {
    clearScreen();
    if (studentCount >= MAX_STUDENTS) {
        printf("学生数量已达上限!\n");
        waitKey();
        return;
    }

    Student s;
    printf("\n════════ 添加学生 ════════\n");
    
    printf("学号: "); scanf("%s", s.id); CLEAN_INPUT();
    printf("姓名: "); scanf("%s", s.name); CLEAN_INPUT();
    printf("学院: "); scanf("%s", s.academy); CLEAN_INPUT();
    printf("班级: "); scanf("%s", s.className); CLEAN_INPUT();
    printf("性别: "); scanf("%s", s.gender); CLEAN_INPUT();
    printf("年龄: "); scanf("%d", &s.age); CLEAN_INPUT();
    printf("身份证号: "); scanf("%s", s.idNumber); CLEAN_INPUT();

    students[studentCount++] = s;
    printf("\n学生信息已添加!\n");
    waitKey();
}

// 按学号查询
void searchById() {
    clearScreen();
    char id[20];
    printf("\n════════ 按学号查询 ════════\n");
    printf("请输入学号: "); scanf("%s", id); CLEAN_INPUT();

    int found = 0;
    for (int i = 0; i < studentCount; i++) {
        if (strcmp(students[i].id, id) == 0) {
            printf("\n学号: %s\n", students[i].id);
            printf("姓名: %s\n", students[i].name);
            printf("学院: %s\n", students[i].academy);
            printf("班级: %s\n", students[i].className);
            printf("性别: %s\n", students[i].gender);
            printf("年龄: %d\n", students[i].age);
            printf("身份证号: %s\n", students[i].idNumber);
            found = 1;
            break;
        }
    }

    if (!found) printf("\n未找到该学号的学生!\n");
    waitKey();
}

// void searchById() {
//     clearScreen();
//     char id[20];
//     printf("\n════════ 按学号查询 ════════\n");
//     printf("请输入学号: ");
//     if (scanf("%19s", id) != 1) {  // 安全输入
//         printf("输入无效!\n");
//         CLEAN_INPUT();
//         waitKey();
//         return;
//     }
//     CLEAN_INPUT();

//     // 调试：打印当前所有学号（测试时启用）
//     // for (int i = 0; i < studentCount; i++) {
//     //     printf("DBG: 学号[%d]=%s\n", i, students[i].id);
//     // }

//     int found = 0;
//     for (int i = 0; i < studentCount; i++) {
//         if (strcmp(students[i].id, id) == 0) {
//             printf("\n════════ 查询结果 ════════\n");
//             printf("学号: %s\n", students[i].id);
//             printf("姓名: %s\n", students[i].name);
//             printf("学院: %s\n", students[i].academy);
//             printf("班级: %s\n", students[i].className);
//             printf("性别: %s\n", students[i].gender);
//             printf("年龄: %d\n", students[i].age);
//             printf("身份证号: %s\n", students[i].idNumber);
//             found = 1;
//             break;
//         }
//     }

//     if (!found) {
//         printf("\n⚠️ 未找到学号为 [%s] 的学生!\n", id);
//     }
//     waitKey();
// }

// 按学院查询
void searchByAcademy() {
    clearScreen();
    char academy[50];
    printf("\n════════ 按学院查询 ════════\n");
    printf("请输入学院名称: "); scanf("%s", academy); CLEAN_INPUT();

    int found = 0;
    for (int i = 0; i < studentCount; i++) {
        if (strcmp(students[i].academy, academy) == 0) {
            printf("\n学号: %s", students[i].id);
            printf("\t姓名: %s", students[i].name);
            printf("\t班级: %s\n", students[i].className);
            found = 1;
        }
    }

    if (!found) printf("\n该学院没有学生记录!\n");
    waitKey();
}

// 删除学生
void deleteStudent() {
    clearScreen();
    char id[20];
    printf("\n════════ 删除学生 ════════\n");
    printf("请输入要删除的学生学号: "); scanf("%s", id); CLEAN_INPUT();

    int found = 0;
    for (int i = 0; i < studentCount; i++) {
        if (strcmp(students[i].id, id) == 0) {
            for (int j = i; j < studentCount - 1; j++) {
                students[j] = students[j + 1];
            }
            studentCount--;
            printf("\n学生信息已删除!\n");
            found = 1;
            break;
        }
    }

    if (!found) printf("\n未找到该学号的学生!\n");
    waitKey();
}

// 修改学生信息
void modifyStudent() {
    clearScreen();
    char id[20];
    printf("\n════════ 修改学生信息 ════════\n");
    printf("请输入要修改的学生学号: "); scanf("%s", id); CLEAN_INPUT();

    int found = 0;
    for (int i = 0; i < studentCount; i++) {
        if (strcmp(students[i].id, id) == 0) {
            printf("\n当前信息:\n");
            printf("1. 学号: %s\n", students[i].id);
            printf("2. 姓名: %s\n", students[i].name);
            printf("3. 学院: %s\n", students[i].academy);
            printf("4. 班级: %s\n", students[i].className);
            printf("5. 性别: %s\n", students[i].gender);
            printf("6. 年龄: %d\n", students[i].age);
            printf("7. 身份证号: %s\n", students[i].idNumber);

            printf("\n请输入要修改的项(1-7): ");
            int choice;
            scanf("%d", &choice); CLEAN_INPUT();

            switch (choice) {
                case 1: printf("新学号: "); scanf("%s", students[i].id); CLEAN_INPUT(); break;
                case 2: printf("新姓名: "); scanf("%s", students[i].name); CLEAN_INPUT(); break;
                case 3: printf("新学院: "); scanf("%s", students[i].academy); CLEAN_INPUT(); break;
                case 4: printf("新班级: "); scanf("%s", students[i].className); CLEAN_INPUT(); break;
                case 5: printf("新性别: "); scanf("%s", students[i].gender); CLEAN_INPUT(); break;
                case 6: printf("新年龄: "); scanf("%d", &students[i].age); CLEAN_INPUT(); break;
                case 7: printf("新身份证号: "); scanf("%s", students[i].idNumber); CLEAN_INPUT(); break;
                default: printf("无效选择!\n"); break;
            }

            printf("\n学生信息已更新!\n");
            found = 1;
            break;
        }
    }

    if (!found) printf("\n未找到该学号的学生!\n");
    waitKey();
}

// 数据统计
void statistics() {
    clearScreen();
    printf("\n════════ 数据统计 ════════\n");
    printf("学生总数: %d\n", studentCount);

    if (studentCount == 0) {
        waitKey();
        return;
    }

    // 按学院统计
    printf("\n按学院统计:\n");
    char academies[MAX_STUDENTS][50];
    int academyCounts[MAX_STUDENTS] = {0};
    int uniqueAcademyCount = 0;

    for (int i = 0; i < studentCount; i++) {
        int found = 0;
        for (int j = 0; j < uniqueAcademyCount; j++) {
            if (strcmp(students[i].academy, academies[j]) == 0) {
                academyCounts[j]++;
                found = 1;
                break;
            }
        }
        if (!found) {
            strcpy(academies[uniqueAcademyCount], students[i].academy);
            academyCounts[uniqueAcademyCount] = 1;
            uniqueAcademyCount++;
        }
    }

    for (int i = 0; i < uniqueAcademyCount; i++) {
        printf("%s: %d人\n", academies[i], academyCounts[i]);
    }

    waitKey();
}

// 显示菜单
void showMenu() {
    clearScreen();
    printf("\n════════ 学生信息管理系统 ════════\n");
    printf("1. 添加学生\n");
    printf("2. 按学号查询\n");
    printf("3. 按学院查询\n");
    printf("4. 删除学生\n");
    printf("5. 修改信息\n");
    printf("6. 数据统计\n");
    printf("7. 退出系统\n");
    printf("══════════════════════════════════\n");
    printf("请选择操作: ");
}

int main() {
    loadFromFile();
    int choice;

    while (1) {
        showMenu();
        scanf("%d", &choice);
        CLEAN_INPUT();

        switch (choice) {
            case 1: addStudent(); break;
            case 2: searchById(); break;
            case 3: searchByAcademy(); break;
            case 4: deleteStudent(); break;
            case 5: modifyStudent(); break;
            case 6: statistics(); break;
            case 7: saveToFile(); exit(0);
            default: 
                printf("无效选择，请重新输入!\n");
                waitKey();
        }
    }
    return 0;
}
